package com.example.yls.wuziqidemo;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.PointF;
import android.icu.util.Measure;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;

import java.util.ArrayList;

/**
 * Created by yls on 2018/6/13.
 */

public class WuziqiPanel extends View {
    private int panelWidth;
    private float itemSize;
    private int MAX_ITEMS = 10;
    private Paint paint = new Paint();

    private Bitmap mWhitePiece;
    private Bitmap mBlackPiece;

    private float ratioPieceOfLineHeight = 3*1.0f / 4;

    private ArrayList<Point> mWhiteArray = new ArrayList<>();
    private ArrayList<Point> mBlackArray = new ArrayList<>();

    private boolean mIsWhite = true;

    private boolean mIsGameOver;
    private boolean mIsWhiteWinner;


    private Point mPoint;

    public WuziqiPanel(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);

//        setBackgroundColor(0x44FF0000);
        init();
    }

    private void init() {
        paint.setColor(0x88000000);
        paint.setAntiAlias(true);
        paint.setDither(true);
        paint.setStyle(Paint.Style.STROKE);

        mWhitePiece = BitmapFactory.decodeResource(getResources(),R.drawable.stone_w2);
        mBlackPiece = BitmapFactory.decodeResource(getResources(),R.drawable.stone_b1);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        int width = MeasureSpec.getSize(widthMeasureSpec);
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);

        int height = MeasureSpec.getSize(heightMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);

        Log.e("WUziqiPanel","onMeasure w="
                + width + "h = " + height);
        int result = Math.min(width,height);
        if (widthMode == MeasureSpec.UNSPECIFIED) {
            result = height;
        } else if (heightMode == MeasureSpec.UNSPECIFIED) {
            result = width;
        }
        setMeasuredDimension(result,result);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        Log.e("WUziqiPanel","onSizeChanged w="
                + w + "h = " + h);

        panelWidth = w;
        itemSize = panelWidth * 1.0f / MAX_ITEMS;

        int pieceWidth = (int) (itemSize * ratioPieceOfLineHeight);
        mWhitePiece = Bitmap.createScaledBitmap(mWhitePiece,pieceWidth,pieceWidth,false);
        mBlackPiece = Bitmap.createScaledBitmap(mBlackPiece,pieceWidth,pieceWidth,false);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (mIsGameOver) {
            return false;
        }
        int action = event.getAction();

        if (action == MotionEvent.ACTION_UP) {
            int x = (int) event.getX();
            int y = (int) event.getY();
            Point p = getValibPoint(x,y);

            if (mWhiteArray.contains(p) || mBlackArray.contains(p)) {
                return false;
            }
            if (mIsWhite) {
                mWhiteArray.add(p);
            } else {
                mBlackArray.add(p);
            }
            invalidate();
            mIsWhite = !mIsWhite;
        }
        if (action == MotionEvent.ACTION_DOWN) {
            return true;
        }
        return super.onTouchEvent(event);
    }

    private Point getValibPoint(int x, int y) {
        return new Point((int) (x / itemSize),(int) (y / itemSize));
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        drawBoard(canvas);
        drawPieces(canvas);
        checkGameOver();
    }

    private void checkGameOver() {
        boolean whiteWin = checkFiveInLine(mWhiteArray);
        boolean blackWin = checkFiveInLine(mBlackArray);
        if (whiteWin || blackWin) {
            mIsGameOver = true;
            mIsWhiteWinner = whiteWin;
            String text = mIsWhiteWinner ? "白棋胜利" : "黑棋胜利";
            Toast.makeText(getContext(),text,Toast.LENGTH_SHORT).show();
        }
    }

    private boolean checkFiveInLine(ArrayList<Point> points) {
        for (Point p : points) {
            int x = p.x;
            int y = p.y;
            boolean win = CheckWin.checkHorizontal(x,y,points);
            if (win) {
                return true;

            }
            win = CheckWin.checkVertical(x,y,points);
            if (win) {
                return true;
            }
            win = CheckWin.checkLeftDiagonal(x,y,points);
            if (win) {
                return true;
            }
            win = CheckWin.checkRightDiagonal(x,y,points);
            if (win) {
                return true;
            }
        }
        return false;
    }

    private void drawPieces(Canvas canvas) {
        for (int i = 0,n= mWhiteArray.size();i<n;i++) {
            Point whitePoint = mWhiteArray.get(i);
            canvas.drawBitmap(mWhitePiece,
                    (whitePoint.x + (1-ratioPieceOfLineHeight) / 2) * itemSize,
                    (whitePoint.y + (1-ratioPieceOfLineHeight) /2) * itemSize,null);
        }

        for (int i = 0,n = mBlackArray.size(); i<n;i++) {
            Point blackPoint = mBlackArray.get(i);
            canvas.drawBitmap(mBlackPiece,
                    (blackPoint.x + (1-ratioPieceOfLineHeight) / 2) * itemSize,
                    (blackPoint.y + (1-ratioPieceOfLineHeight) /2) * itemSize,null);
        }
    }

    private void drawBoard(Canvas canvas) {

        int w = panelWidth;
        float lineHeight = itemSize;
        for (int i = 0; i<MAX_ITEMS; i++) {
            int startX = (int) (itemSize/2);
            int endX = (int) (panelWidth-(itemSize/2));
            int startY = (int) ((0.5 + i) * lineHeight);
            int endY = (int) ((0.5 + i) * lineHeight);

            canvas.drawLine(startX,startY,endX,endY,paint);
        }
        for (int i = 0; i<MAX_ITEMS;i++) {
            int startX = (int) ((0.5 + i) * lineHeight);
            int endX = (int) ((0.5 + i) * lineHeight);
            int startY = (int) (lineHeight / 2);
            int endY = (int) (w - lineHeight / 2);
            canvas.drawLine(startX,startY,endX,endY,paint);
        }
    }

    public void reStart() {
        mWhiteArray.clear();
        mBlackArray.clear();
        mIsGameOver = false;
        mIsWhiteWinner = false;

        invalidate();
    }

    public void Return() {
        if (mIsWhite) {
            if (mBlackArray != null && !mBlackArray.isEmpty()) {
                mBlackArray.remove(mBlackArray.size() - 1);
                if (mWhiteArray != null && !mWhiteArray.isEmpty()) {
                    mPoint = mWhiteArray.get(mWhiteArray.size() - 1);
                }
                mIsWhite = !mIsWhite;
                mIsGameOver = false;
                mIsWhiteWinner = false;
                invalidate();
                return;
            }
        } else if (!mIsWhite) {
            if (mWhiteArray != null && !mWhiteArray.isEmpty()) {
                mWhiteArray.remove(mWhiteArray.size() -1);
                if (mBlackArray != null && !mBlackArray.isEmpty()) {
                    mPoint = mBlackArray.get(mBlackArray.size() - 1);
                }
                mIsWhite = !mIsWhite;
                mIsGameOver = false;
                mIsWhiteWinner = false;
                invalidate();
                return;
            }
        }
    }

    private static final String INSTANCE = "instance";
    private static final String INSTANCE_GAME_OVER = "instance_game_over";
    private static final String INSTANCE_WHITE_ARRAY = "instance_white_array";
    private static final String INSTANCE_BLACK_ARRAY = "instance_black_array";
    private static final String INSTANCE_mIsWhite = "instance_mIsWhite";

    @Override
    protected Parcelable onSaveInstanceState() {
        Bundle bundle = new Bundle();
        bundle.putParcelable(INSTANCE,super.onSaveInstanceState());

        bundle.putBoolean(INSTANCE_GAME_OVER,mIsGameOver);
        bundle.putParcelableArrayList(INSTANCE_WHITE_ARRAY,mWhiteArray);
        bundle.putParcelableArrayList(INSTANCE_BLACK_ARRAY,mBlackArray);
        bundle.putBoolean(INSTANCE_mIsWhite,mIsWhite);
        return bundle;

    }

    @Override
    protected void onRestoreInstanceState(Parcelable state) {
        if (state instanceof Bundle) {
            Bundle bundle = (Bundle) state;
            mIsGameOver = bundle.getBoolean(INSTANCE_GAME_OVER);
            mWhiteArray = bundle.getParcelableArrayList(INSTANCE_WHITE_ARRAY);
            mBlackArray = bundle.getParcelableArrayList(INSTANCE_BLACK_ARRAY);
            mIsWhite = bundle.getBoolean(INSTANCE_mIsWhite);
            super.onRestoreInstanceState(bundle.getParcelable(INSTANCE));
            return;
        }
        super.onRestoreInstanceState(state);
    }
}
